package yxy.game.pm2.module.union;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map.Entry;
import java.util.Set;

import org.redisson.api.RMap;

import yxy.apple.util.StringUtillity;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.game.base.redis.RedisManager;
import yxy.game.pm2.bean.module.BaseGameRedisBean;

/** 联盟名字管理 */
public class UnionName extends BaseGameRedisBean {

	static UnionName instance;

	public static UnionName getInstance() {
		if (instance == null) {
			instance = new UnionName();
		}
		return instance;
	}

	private UnionName() {
	}

	public String checkName(String name) {
		name = StringUtillity.toDBC(name).trim().replaceAll(" ", "");
		if (name.length() <= 0) {
			return null;
		}
		return name;
	}

	// redis==========================================================================

	private static String key() {
		return "NAME:UNION";
	}

	static private RMap<String, String> touch() throws RedisException {
		return RedisManager.client(redis()).getMap(key());
	}

	public void add(UnionBean union) {
		try {
			touch().put(union.getCode(), union.getName());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	static public Collection<String> search(String keyword) {
		ArrayList<String> result = new ArrayList<>();
		try {
			Set<Entry<String, String>> values = touch().readAllEntrySet();
			for (Entry<String, String> entry : values) {
				if (entry.getValue().contains(keyword)) {
					result.add(entry.getKey());
				}
			}
		} catch (RedisException e) {
			e.printStackTrace();
		}
		return result;
	}

	public boolean exist(String name) {
		try {
			return touch().containsValue(name);
		} catch (RedisException e) {
			e.printStackTrace();
		}
		return true;
	}

	public void delete(UnionBean union) {
		try {
			touch().remove(union.getCode());
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}
	// lock==========================================================================

	@Override
	public String lockKey() {
		return String.format("lock:%s", key());
	}
}
